package com.ruoyi.video.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.video.domain.Device;
import com.ruoyi.video.mapper.DeviceMapper;
import com.ruoyi.video.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备Service业务层处理
 *
 * @author orange
 * @date 2025-01-14
 */
@Service
public class DeviceServiceImpl implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备
     *
     * @param deviceId 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceByDeviceId(Long deviceId) {
        return deviceMapper.selectDeviceByDeviceId(deviceId);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        device.setUrl(this.generateRtspUrl(device));
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insertDevice(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        device.setUrl(this.generateRtspUrl(device));
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateDevice(device);
    }

    /**
     * 批量删除设备
     *
     * @param deviceIds 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByDeviceIds(Long[] deviceIds) {
        return deviceMapper.deleteDeviceByDeviceIds(deviceIds);
    }

    /**
     * 删除设备信息
     *
     * @param deviceId 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByDeviceId(Long deviceId) {
        return deviceMapper.deleteDeviceByDeviceId(deviceId);
    }

    /**
     * 生成rtsp地址
     * @param device
     * @return
     */
    private String generateRtspUrl(Device device) {
        String ip = device.getIp();
        String userName = device.getUserName();
        String password = device.getPassword();
        int port = 554;

        if ("1".equals(device.getType())) {
            return String.format("rtsp://%s:%s@%s:%d/Streaming/Channels/2", userName, password, ip, port);
        } else if ("2".equals(device.getType())) {
            return String.format("rtsp://%s:%s@%s:%d/cam/realmonitor?channel=1&subtype=0", userName, password, ip, port);
        } else {
            throw new RuntimeException("网络异常，请检查网络！");
        }
    }

}
